package com.fieldchain.ex.fa100.utils.net.action;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.utils.net.modle.ImageRequest;
import com.fieldchain.ex.fa100.utils.net.tools.MainHandler;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 文件描述：
 * 创 建 人：byl
 * 创建时间：2017/9/5 0005 18:14
 */
public class GetImageRequest {
    public static void getRequest(String url, final ImageRequest re, OkHttpClient okHttpClient, final String tags) {
        //创建一个Request
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        //发起异步请求，并加入回调
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                MainHandler.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new BaseEvent(2,tags));
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                byte[] img = response.body().bytes();
                final Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
//                CookeiUtils.saveCookei(response);
                MainHandler.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new BaseEvent(2,tags));
                        re.imgReceive(bitmap);
                    }
                });
            }
        });
    }
}
